<template>
<div class="page-wrapper">
    <div class="page-wrapper__body">
        <div class="page-container is-form"  v-loading="isLoading">
        <el-row>
            <el-col :span="24">
                <el-upload
                        class="upload-demo"
                        ref="upload"
                        :action="uploadAction"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        :on-change="readExcel"
                        :limit="1"
                        :file-list="fileList"
                        :auto-upload="false">
                    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
                </el-upload>
            </el-col>
            <el-col :span="24">
                <div class="up-total" v-show="textShow">
                    <p><span>可上传人数: </span>请先上传文件</p>
                    <p><span>不可上传人数: </span>请先上传文件</p>
                </div>
                <div class="up-total" v-show="!textShow">
                    <p><span>可上传人数: </span><strong style="color: #3a835d">{{successCount}}</strong> 人</p>
                    <p><span>不可上传人数: </span><strong style="color: red">{{errorCount}}</strong> 人</p>
                </div>
            </el-col>
			<el-col :span="24" style="margin-top:30px;">
				<el-button size="small" type="success" @click="submitUpload">上传</el-button>
			</el-col>
        </el-row>
		</div>
		</div>
    </div>
</template>

<script>
    import XLSX from 'xlsx';
    import {importExcel, saveList} from '../../api/student'

    export default {
        name: "import",
        data() {
            return {
                isLoading:false,
                uploadAction:'',
                fileList: [],
                successList:{},
                successCount:0,
                errorCount:0,
                textShow: true,
            };
        },
        methods: {
            submitUpload() {
                this.$confirm('确定上传文件?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //this.$refs.upload.submit();
                    //console.log(this.successList);
                    if(this.successCount === 0){
                        this.$message({
                            type: 'warning',
                            message: '可上传文件为0，请重新选择!'
                        });
                        return false;
                    }
                    this.saveSuccessList(this.successList);
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消上传'
                    });
                });
            },
            readExcel(file) {
                this.isLoading = true;
                var suffix = file.name.split(".")[1]
                if(suffix != 'xls' && suffix !='xlsx'){
                    this.isLoading = false;
                    this.$message.warning('文件类型不正确！');
                    return false;
                }
                const fileReader = new FileReader();
                fileReader.onload = (ev) => {
                    try {
                        const data = ev.target.result;
                        const workbook = XLSX.read(data, {
                            type: 'binary'
                        });
                        for (let sheet in workbook.Sheets) {
                            const sheetArray = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
                            if(sheetArray!=null && sheetArray.length >0){
                                //console.log("sheetArray",sheetArray);
                                this.importData(sheetArray);
                            }
                        }
                        // this.$message.success('导入完成！');
                    }catch (e) {
                        this.isLoading = false;
                        this.$message.warning('文件类型不正确！');
                        return false;
                    }
                };
                this.isLoading = false;
                fileReader.readAsBinaryString(file.raw);
            },
            handleRemove(file, fileList) {
                //this.fileList = [];
                this.textShow = true;
                this.successCount = 0;
                this.errorCount = 0;
                //console.log(file, fileList);
            },
            handlePreview(file) {
                console.log(file);
            },
            async saveSuccessList(list){
                this.isLoading = true;
                let resp = await saveList({list:list});
                if(!this.qUtil.validResp(resp)){
                    this.$message.error(resp.errMsg || '上传失败');
                    this.isLoading = false;
                }else{
                    this.$message({
                        type: 'success',
                        message: '上传成功!'
                    });
                }
                this.fileList = [];
                this.textShow = true;
                this.isLoading = false;
                this.$router.push("/studentList");
            },
            async importData(sheetArray){
                this.isLoading = true;
                let telList = sheetArray.map(m=>m['电话']);
                let resp = await importExcel({mapList:sheetArray, telList:telList});
                console.log("====resp",resp);
                if(!this.qUtil.validResp(resp)){
                    this.$message.error(resp.errMsg || '导入失败')
                    this.isLoading = false;
                    return false;
                }
                this.isLoading = false;
                this.textShow = false;
                this.errorCount = resp.data.errorCount;
                this.successCount = resp.data.successCount;
                this.successList = resp.data.successList;
            },

        }
    }
</script>

<style lang="scss" scoped>
.up-total{
	margin-top:30px;
	p{
		line-height: 2;
		font-size:14px;
		color:#666;
		span{
			display: inline-block;
			width:100px;
		}
	}
}
</style>